/*
 * IRReceiver.c
 *
 *  Created on: Mar 9, 2011
 *      Author: wli3
 */

#include <LCD4Bit_mod.h>
LCD4Bit_mod lcd = LCD4Bit_mod(2);
#define TIMER_RESET TCNT1 = 0
#define SAMPLE_SIZE 68
int BUZZER = 16;// 设置模拟口2 为蜂鸣器信号输出引脚
int IRpin = 15; //设置模拟口1 为信号接收引脚
unsigned int TimerValue[SAMPLE_SIZE];
char direction[SAMPLE_SIZE];
byte change_count;
long time1, time2;
unsigned long data;
char a, b, c, d, e;
unsigned long irc;
char tab[12] = { "0123456789" };
void setup() {
	pinMode(IRpin, INPUT);
	pinMode(13, OUTPUT);
	pinMode(BUZZER, OUTPUT);//设置与蜂鸣器连接的引脚为输出模式
	lcd.init();
	lcd.clear();
	lcd.printIn("www.robotbase.cn");
	lcd.cursorTo(2, 0);
	lcd.printIn("IR_CODE:");
	TCCR1B = 0x03;
	TCCR1A = 0x00;
	a = 0;
	b = 0;
	c = 0;
	d = 0;
	e = 0;
	Serial.begin(9600);
	bee();
}
void loop() {
	lcd.cursorTo(2, 9);
	lcd.print(tab[a]);
	lcd.cursorTo(2, 10);
	lcd.print(tab[b]);
	lcd.cursorTo(2, 11);
	lcd.print(tab[c]);
	lcd.cursorTo(2, 12);
	lcd.print(tab[d]);
	lcd.cursorTo(2, 13);
	lcd.print(tab[e]);
	ir_code();
	Serial.println(irc);
}
void bee() {
	digitalWrite(BUZZER, LOW);//蜂鸣器响
	delay(300);
	digitalWrite(BUZZER, HIGH);//蜂鸣器响
	delay(300);
}
void ir_code() {
	change_count = 0;
	while (digitalRead(IRpin) == HIGH) {
	} // 等待起始位
	TIMER_RESET;
	TimerValue[change_count] = TCNT1;
	direction[change_count++] = '0';
	while (change_count < SAMPLE_SIZE) {
		if (direction[change_count - 1] == '0') {
			while (digitalRead(IRpin) == LOW) {
			} // 等待电平上升沿出现
			TimerValue[change_count] = TCNT1;
			direction[change_count++] = '1'; // 保持信号状态
		} else {
			while (digitalRead(IRpin) == HIGH) {
			} // 等待电平信号的下降沿
			TimerValue[change_count] = TCNT1;
			direction[change_count++] = '0'; // 保持信号状态
		}
	}
	change_count = 0;
	data = 0;
	time1 = (long) TimerValue[change_count] * 4;
	change_count += 2;
	while (change_count < SAMPLE_SIZE) {
		time2 = (long) TimerValue[change_count] * 4;
		if ((time2 - time1) > 8000) {
		} else if ((time2 - time1) > 1680) {
			data = data << 1; // 左移一位
			data |= 1;
		} else {
			data = data << 1;
		}
		change_count += 2;
		time1 = time2;
	}
	irc = data % 100000;
	a = irc / 10000;
	b = irc % 10000 / 1000;
	c = irc % 1000 / 100;
	d = irc % 100 / 10;
	e = irc % 10;
	bee();
}
